package com.chang.bootplus.controller.execl;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.controller.storage.local.LocalService;
import com.chang.bootplus.controller.storage.local.LocalYml;
import com.chang.bootplus.entity.School;
import com.chang.bootplus.entity.StuExecl;
import com.chang.bootplus.entity.Student;
import com.chang.bootplus.po.ExcelIdPO;
import com.chang.bootplus.po.ExcelPO;
import com.chang.bootplus.service.SchoolService;
import com.chang.bootplus.service.StuExeclService;
import com.chang.bootplus.service.StudentService;
import com.chang.bootplus.vo.ExcelVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;


@Api(tags = {"excel导入"})
@RestController
@RequestMapping("/execl")
public class ExcelController {

    @Autowired
    LocalYml localYml;

    @Autowired
    SchoolService schoolService;


    @Autowired
    StuExeclService stuExeclService;

    @Autowired
    LocalService localService;

    @Autowired
    StudentService studentService;
//

    @ApiOperation(value = "Execl文件导入")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "file",
                    value = "文件",
                    required = true,
                    dataType = "__File"
            ),
            @ApiImplicitParam(
                    name = "schoolName",
                    value = "学校名称",
                    defaultValue = "test"
            )
    })
    @PostMapping("upload")
    public ApiResponse<Void> test3(@RequestParam(value = "file") MultipartFile file,@RequestParam String schoolName,@RequestParam String uploadTime){
        String nickname =(String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, nickname));

        if (!one.getSchoolName().equals(schoolName)&&!one.getSchoolName().equals("admin")){
            throw new BusException("你无法导入其他学校的成绩");
        }
        localService.uploadExcel(file,schoolName,uploadTime);
        String dateStr = uploadTime+" 00:00:00";
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        //格式化创建时间即为parse
        LocalDateTime parse = LocalDateTime.parse(dateStr, dateTimeFormatter);
//        try {
//            EasyExcel.read("C:/Users/jokehe/Desktop/"+file.getOriginalFilename(), DemoData.class, new DemoDataListener(studentService,schoolName,parse)).sheet().doRead();
            EasyExcel.read("excel/"+file.getOriginalFilename(), DemoData.class, new DemoDataListener(studentService,schoolName,parse)).sheet().doRead();
//        }catch (Exception e){
//            throw new BusException("文件格式错误");
//        }
        saveExecl(file, schoolName, uploadTime);
        // 测试用
        HashMap<String, Object> map = new HashMap<>();
        map.put("execlurl",localYml.getVisitAddress2()+"/do_one_do/"+"excel/"+file.getOriginalFilename());
        return new ApiResponse(map).setReMsg("导入成功");
    }

    private void saveExecl(MultipartFile file,String schoolName,String uploadTime) {
        String fileName = file.getOriginalFilename();
        String filePath = localYml.getUploadAddress2()+"/"+"do_one_do/excel";
        String saveurl="/do_one_do/"+"excel/"+file.getOriginalFilename();
        String dateStr = uploadTime+" 00:00:00";
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        StuExecl stuExecl = new StuExecl().setExcelName(fileName).setExcelUrl(saveurl).setSchoolName(schoolName);
        stuExecl.setGmtCreate(LocalDateTime.parse(dateStr, dateTimeFormatter));
        stuExeclService.save(stuExecl);
    }

    @PostMapping("/deleteExecls")
    @ApiOperation(httpMethod = "POST", value = "excel文件删除")
    public ApiResponse<Void> deleteExecl(@RequestBody ExcelIdPO po){
        boolean b = stuExeclService.removeById(po.getId());
        if (!b){
            throw new BusException("删除失败");
        }
        return new ApiResponse("删除成功");
    }

    @PostMapping("/getExecls")
    @ApiOperation(httpMethod = "POST", value = "excel文件列表")
    public ApiResponse<ExcelVO> testww3(@RequestBody ExcelPO po){
        String nickname =(String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, nickname));

        int countAll=stuExeclService.count(new LambdaQueryWrapper<StuExecl>()
                .eq(!one.getSchoolName().equals("admin"),StuExecl::getSchoolName,one.getSchoolName())
                .like(po.getProjectName()!=null,StuExecl::getExcelName,po.getProjectName())
                .like(po.getUploadTime()!=null,StuExecl::getGmtCreate,po.getUploadTime()));

        Page<StuExecl> stuExeclPage = new Page<>(po.getPageNumber(), po.getPageSize());
        System.out.println(po.getPageNumber()+"---");
        System.out.println(po.getPageSize()+"---");
        Page<StuExecl> page = stuExeclService.page(stuExeclPage, new LambdaQueryWrapper<StuExecl>()
                .eq(!one.getSchoolName().equals("admin"), StuExecl::getSchoolName, one.getSchoolName())
                .like(po.getProjectName() != null, StuExecl::getExcelName, po.getProjectName())
                .like(po.getUploadTime() != null, StuExecl::getGmtCreate, po.getUploadTime()));
        List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
        return new ApiResponse<>(excelVOS,new Long(excelVOS.size()),new Long(countAll));


//        if (!one.getSchoolName().equals("admin")){
////            countAll=stuExeclService.count(new LambdaQueryWrapper<StuExecl>()
////                    .eq(StuExecl::getSchoolName,one.getSchoolName()).like(StuExecl::getExcelName,po.getProjectName()).like(StuExecl::getGmtCreate,po.getUploadTime()));
//            stuExeclPage = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().eq(StuExecl::getSchoolName,one.getSchoolName()));
//            if (po.getProjectName()==null&&po.getUploadTime()==null){
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(stuExeclPage.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,stuExeclPage.getTotal(),new Long(countAll));
//            }else if (po.getProjectName()!=null&&po.getUploadTime()==null){
//                Page<StuExecl> page = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().like(StuExecl::getExcelName,po.getProjectName()));
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,page.getTotal(),new Long(countAll));
//            }else if (po.getProjectName()==null&&po.getUploadTime()!=null) {
//                Page<StuExecl> page = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().like(StuExecl::getGmtCreate,po.getUploadTime()));
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,page.getTotal(),new Long(countAll));
//            }else {
//                Page<StuExecl> page = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().like(StuExecl::getExcelName,po.getProjectName()).like(StuExecl::getGmtCreate,po.getUploadTime()));
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,page.getTotal(),new Long(countAll));
//            }
//        }else {
//            countAll=stuExeclService.count();
//            stuExeclPage = stuExeclService.page(stuExeclPage);
//            if (po.getProjectName()==null&&po.getUploadTime()==null){
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(stuExeclPage.getRecords(), ExcelVO.class);
//                System.out.println(stuExeclPage.getRecords().size());
//                System.out.println(excelVOS.size());
//                return new ApiResponse<>(excelVOS,new Long(excelVOS.size()) ,new Long(countAll));
//            }else if (po.getProjectName()!=null&&po.getUploadTime()==null){
//                Page<StuExecl> page = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().like(StuExecl::getExcelName,po.getProjectName()));
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,page.getTotal(),new Long(countAll));
//            }else if (po.getProjectName()==null&&po.getUploadTime()!=null) {
//                Page<StuExecl> page = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().like(StuExecl::getGmtCreate,po.getUploadTime()));
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,page.getTotal(),new Long(countAll));
//            }else {
//                Page<StuExecl> page = stuExeclService.page(stuExeclPage,new LambdaQueryWrapper<StuExecl>().like(StuExecl::getExcelName,po.getProjectName()).like(StuExecl::getGmtCreate,po.getUploadTime()));
//                List<ExcelVO> excelVOS = BeanUtil.listA2ListB(page.getRecords(), ExcelVO.class);
//                return new ApiResponse<>(excelVOS,page.getTotal(),new Long(countAll));
//            }
//        }
    }




}
